package com.iotechn.unimall.admin.myapi.conform;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.core.util.GeneratorUtil;
import com.iotechn.unimall.data.mapper.mymapper.*;

import com.iotechn.unimall.mydata.domain.*;
import com.iotechn.unimall.mydata.dto.UserAndStudentOrTeacher;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@Service
public class IConformServiceImpl implements IConformService{

    @Autowired
    private IUserMapper iUserMapper;

    @Autowired
    private IClassMapper iClassMapper;

    @Autowired
    private IClassAndStudentMapper iClassAndStudentMapper;

    @Autowired
    private IConformMapper iConformMapper;

    @Autowired
    protected IStudentMapper iStudentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(Integer tid, String cname) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",tid);
        map.put("cname",cname);
        List<ClassBean> classBeans = iClassMapper.selectByMap(map);

        if(classBeans.size()>0){
            throw new AdminServiceException(ExceptionDefinition.CLASSNAME_ALREADY_EXIST);
        }

        String code = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();

        ClassBean classBean = new ClassBean();
        classBean.setUid(tid);
        classBean.setCname(cname);
        classBean.setCode(code);
        iClassMapper.insert(classBean);

        return "入班暗号:"+code;
    }

    @Override
    public List<ClassBean> classList(Integer tid) throws ServiceException {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("uid",tid);
        List<ClassBean> classBeans = iClassMapper.selectByMap(stringObjectHashMap);
        return classBeans;
    }

    @Override
    public String classCode(Integer tid,String cname) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",tid);
        map.put("cname",cname);
        List<ClassBean> classBeans = iClassMapper.selectByMap(map);
        String code = classBeans.get(0).getCode();

        return code;
    }

//    @Override
//    public String uploadExcel(MultipartFile upload) throws ServiceException, IOException {
//
//        String path = ApiController.class.getResource("../../../../../uploads").getFile();
//        File file = new File(path);
//
//        if(!file.exists()) {
//            file.mkdirs();
//        }
//
//        // 获取到上传文件的名称
//        String filename = upload.getOriginalFilename();
//        if(filename!=null&&!(filename.endsWith(".xlsx")||filename.endsWith(".xls"))){
//            throw new AdminServiceException(ExceptionDefinition.FILE_NOT_EXCEL);
//        }
//        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
//        // 把文件的名称唯一化
//        filename = uuid+"_"+filename;
//        // 上传文件
//        upload.transferTo(new File(file,filename));
//
//        return "path:"+path+"/"+filename;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<User> addList(String filename,Integer tid,String cname) throws ServiceException, IOException {

        //1、找到文件所在路径
       // String path = ApiController.class.getResource("../../../../../uploads"+"/"+filename).getFile();
        String path = "E:\\unimall\\unimall\\unimall\\unimall-launcher\\src\\main\\resources\\uploads";
        //2、防止路径中有中文出现乱码
        try {
            path = URLDecoder.decode(path, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //3、读取excel文件薄
        XSSFWorkbook workbook = new XSSFWorkbook(path);

        //4、选择文件薄中读取哪一个表
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        //5、获取表中最大的行数
        int lastRowNum = sheetAt.getLastRowNum();


        ArrayList<User> users = new ArrayList<User>();
        //6、循环遍历行与单元格 存为一个User对象
        for (int i = 1; i < lastRowNum; i++) {
            XSSFRow row = sheetAt.getRow(i);

            User user = new User();
            int lastCellNum =row.getLastCellNum();
            for (int j = 0; j <lastCellNum ; j++) {
                String value="";
                if(row.getCell(j)!=null){
                    row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                    value = row.getCell(j).getStringCellValue();

                    if(j==0&&value!=null&&!"".equals(value)){
                        user.setName(value);
                    }
                    if(j==1&&value!=null&&!"".equals(value)){
                        user.setEmail(value);
                    }
                    if(j==2&&value!=null&&!"".equals(value)){
                        user.setNickname(value);
                    }
                    if(j==3&&value!=null&&!"".equals(value)){
                        user.setPassword(Md5Crypt.md5Crypt(value.getBytes(), "$1$" + user.getEmail().substring(0, 5)));
                    }
                    if(j==4&&value!=null&&!"".equals(value)){
                        user.setPhone(value);
                    }
                }
            }
            if(user.getEmail()!=null)
            users.add(user);
        }


        //创建用户
        for (User user : users) {
            if(user.getPassword()==null){
                //设置默认密码为123456
                user.setPassword(Md5Crypt.md5Crypt("123456".getBytes(), "$1$" + user.getEmail().substring(0, 5)));
            }
            iUserMapper.insert(user);
        }

        //加入班级需要cid uid
        //查找唯一的cid
        ClassBean classBean = iClassMapper.selectOne(new QueryWrapper<ClassBean>().eq("uid", tid).eq("cname", cname));
        Long cid = classBean.getId();

        //获得uid
        for (User user : users) {
            Long uid = user.getId();
            ClassAndStudentBean classAndStudentBean = new ClassAndStudentBean();
            classAndStudentBean.setCid(Integer.parseInt(cid.toString()));
            classAndStudentBean.setUid(Integer.parseInt(uid.toString()));
            iClassAndStudentMapper.insert(classAndStudentBean);
        }
        return users;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Integer tid,String cname) throws ServiceException {

        ClassBean classBean = iClassMapper.selectOne(new QueryWrapper<ClassBean>().eq("uid", tid).eq("cname", cname));
        iClassMapper.deleteById(classBean.getId());
        iClassAndStudentMapper.delete(new QueryWrapper<ClassAndStudentBean>().eq("cid",classBean.getId()));
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteStudent(Integer cid, Integer sid) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",sid);
        map.put("cid",cid);

        iClassAndStudentMapper.deleteByMap(map);
        return null;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String upload(MultipartFile upload,Integer tid,Integer cid) throws ServiceException, IOException {
//
//        String path = ApiController.class.getResource("../../../../../uploads").getFile();
//        File file = new File(path);
//
//        if(!file.exists()) {
//            file.mkdirs();
//        }
//
//        // 获取到上传文件的名称
//        String filename = upload.getOriginalFilename();
//
//        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
//        // 把文件的名称唯一化
//        filename = uuid+"_"+filename;
//        // 上传文件
//        upload.transferTo(new File(file,filename));
//
//        ConformBean conformBean = new ConformBean();
//        conformBean.setCid(cid);
//        conformBean.setIsconform(0);
//        conformBean.setUid(tid);
//        conformBean.setData(filename);
//        conformBean.setTitle("文件资料");
//
//        iConformMapper.insert(conformBean);
//        return "ok";
//    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadConform(Integer userId, Integer cid, String title, String data) throws ServiceException {
        ConformBean conformBean = new ConformBean();
        conformBean.setUid(userId);
        conformBean.setCid(cid);
        conformBean.setTitle(title);
        conformBean.setData(data);
        conformBean.setIsconform(1);
        iConformMapper.insert(conformBean);
        return "ok";
    }

    @Override
    public List<ConformBean> conformList(String cid,Integer pageNo, Integer limit) throws ServiceException {
        Page<ConformBean> page = new Page<>(pageNo, limit);
        iConformMapper.selectPage(page, new QueryWrapper<ConformBean>().eq("isConform",1).eq("cid",cid));
        return page.getRecords();
    }

    @Override
    public List<ConformBean> dataList(String cid,Integer pageNo, Integer limit) throws ServiceException {
        Page<ConformBean> page = new Page<>(pageNo, limit);
        iConformMapper.selectPage(page, new QueryWrapper<ConformBean>().eq("isConform",0).eq("cid",cid));
        return page.getRecords();
    }

    @Override
    public ResponseEntity<byte[]> download(String dataName) throws ServiceException, IOException {

        //String path = ApiController.class.getResource("../../../../../uploads").getFile();
        //String path = ApiController.class.getResource("E:\\unimall\\unimall\\unimall\\unimall-launcher\\src\\main\\resources\\uploads").getFile();
        String path = "E:\\unimall\\unimall\\unimall\\unimall-launcher\\src\\main\\resources\\uploads";
        //3. 通过io流的方式 把 要下载的文件 读入到一个 字节数组中 (相当于一个缓存)
        File f = new File(path,dataName);
        InputStream is = new FileInputStream(f);
        byte[] body = new byte[is.available()];
        is.read(body);//把要下载的文件 都 读到 body 字节数组中了  字节适用于所有的文件

        //4.得到这个body缓存 返回浏览器
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + URLEncoder.encode(f.getName(), "UTF-8"));
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);

        is.close();

        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addClass(Integer userId, String code) throws ServiceException {
        ClassBean classBean = iClassMapper.selectOne(new QueryWrapper<ClassBean>().eq("code", code));
        if(classBean==null) {
            throw new AdminServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_CORRECT);
        }

        Long cid = classBean.getId();

        Integer integer = iClassAndStudentMapper.selectCount(new QueryWrapper<ClassAndStudentBean>().eq("uid", userId).eq("cid", cid));
        if(integer>0){
            throw new AdminServiceException(ExceptionDefinition.STUDENR_ALREADY_EXIST);
        }

        ClassAndStudentBean classAndStudentBean = new ClassAndStudentBean();
        classAndStudentBean.setUid(userId);
        classAndStudentBean.setCid(Integer.parseInt(cid.toString()));
        iClassAndStudentMapper.insert(classAndStudentBean);
        return "ok";
    }

    @Override
    public List<UserAndStudentOrTeacher> listStudent(Integer cid) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("cid",cid);
        List<ClassAndStudentBean> classAndStudentBeans = iClassAndStudentMapper.selectByMap(map);
        ArrayList<UserAndStudentOrTeacher> list = new ArrayList<>();
        for (ClassAndStudentBean classAndStudentBean : classAndStudentBeans) {
            User user = iUserMapper.selectById(classAndStudentBean.getUid());
            Student student = iStudentMapper.selectById(classAndStudentBean.getUid());
            UserAndStudentOrTeacher userAndStudentOrTeacher = new UserAndStudentOrTeacher();

            if(null!=user){
                if (user.getEmail()!=null){
                    userAndStudentOrTeacher.setEmail(user.getEmail());
                }
                if (user.getPassword()!=null){
                    userAndStudentOrTeacher.setPassword(user.getPassword());
                }
                if(user.getName()!=null){
                    userAndStudentOrTeacher.setName(user.getName());
                }
                if (user.getNickname()!=null){
                    userAndStudentOrTeacher.setNickname(user.getNickname());
                }
                if (user.getPhone()!=null){
                    userAndStudentOrTeacher.setPhone(user.getPhone());
                }
                if (user.getLoginType()!=null){
                    userAndStudentOrTeacher.setLoginType(user.getLoginType());
                }
            }

            if (null!=student){
                if (student.getSno()!=null){
                    userAndStudentOrTeacher.setSno(student.getSno());
                }
                if (student.getDegree()!=null){
                    userAndStudentOrTeacher.setDegree(student.getDegree());
                }
                if (student.getDepartment()!=null){
                    userAndStudentOrTeacher.setDepartment(student.getDepartment());
                }
                if (student.getGarde()!=null){
                    userAndStudentOrTeacher.setGarde(student.getGarde());
                }
                if (student.getMyclass()!=null){
                    userAndStudentOrTeacher.setMyclass(student.getMyclass());
                }
                if (student.getMajor()!=null){
                    userAndStudentOrTeacher.setMajor(student.getMajor());
                }
                if (student.getSchool()!=null){
                    userAndStudentOrTeacher.setSchool(student.getSchool());
                }
            }

            list.add(userAndStudentOrTeacher);
        }
        return list;
    }

    @Override
    public List<Integer> getClass(Integer userId) throws ServiceException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",userId);
        List<ClassAndStudentBean> classAndStudentBeans = iClassAndStudentMapper.selectByMap(map);
        ArrayList<Integer> strings = new ArrayList<>();
        for (ClassAndStudentBean classAndStudentBean : classAndStudentBeans) {
            strings.add(classAndStudentBean.getCid());
        }
        return strings;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String logoutClass(Integer userId, Integer cid) throws ServiceException {
        iClassAndStudentMapper.delete(new QueryWrapper<ClassAndStudentBean>().eq("uid",userId).eq("cid",cid));
        return null;
    }
}
